package com.ccsu.mymarket.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ccsu.mymarket.controller.utils.DataUtils;
import com.ccsu.mymarket.entity.ShoppingCart;
import com.ccsu.mymarket.entity.message.Meta;
import com.ccsu.mymarket.entity.message.Result;
import com.ccsu.mymarket.jwt.UserLoginToken;
import com.ccsu.mymarket.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@UserLoginToken
@RestController
@RequestMapping("/shoppingcart")
public class ShoppingCartController {
    private ShoppingCartService cartService;

    public ShoppingCartController(@Autowired ShoppingCartService cartService) {
        this.cartService = cartService;
    }

    @GetMapping("/page/{id}")
//    查询到的数据若为空则为 空list []，不为null
//    传入用户id
    public Result getCarts(@PathVariable Integer id) {
        List<ShoppingCart> cartList = cartService.list(new LambdaQueryWrapper<ShoppingCart>()
                .eq(ShoppingCart::getAccId, id));
        if (cartList == null)
            return new Result(new Meta(201, "暂无数据"), cartList);
        return new Result(new Meta(200, "查询成功！"), cartList);
    }

    @PostMapping("/add")
//    按照 ShoppingCart 实体类传入所有必需字段，除时间和id外
    public Result addCart(@RequestBody ShoppingCart cart) {
        cart.setLatestTime(DataUtils.getDateTime(1));
        if (cartService.save(cart))
            return new Result(new Meta(200, "添加成功！"), null);
        return new Result(new Meta(500, "操作失败！"), null);
    }

    /**
     * 删除购物车记录
     *
     * @param data 包含 type + id
     *             type为 1 时：按照 购物车记录 id 删除,传入购物车记录 id
     *             type为 0 时：按照 用户 id 删除，传入用户 id,即清空购物车
     * @return
     */
    @DeleteMapping("/delete")
    public Result deleteCart(@RequestBody Map data) {
        if (data == null)
            return new Result(new Meta(403, "请输入有效数据！"), null);
        Integer type = (Integer) data.get("type");
        Integer id = (Integer) data.get("id");
        if (cartService.deleteCart(type, id))
            return new Result(new Meta(200, "删除成功！"), null);
        return new Result(new Meta(500, "操作失败！"), null);
    }

    @PutMapping("/update")
//    传入 用户 id + 修改后的商品数量 + 商品 id
//    按照ShoppingCart类命名字段
    public Result updateCart(@RequestBody ShoppingCart cart) {
        if (cartService.updateCart(cart))
            return new Result(new Meta(200, "更新成功！"), null);
        return new Result(new Meta(500, "修改失败！"), null);
    }
}
